package org.example.runningforum.Controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.runningforum.modle.*;
import org.example.runningforum.server.ArticleService;
import org.example.runningforum.server.ArticleTopicService;
import org.example.runningforum.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/articles")
public class ArticlesController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleTopicService articleTopicService;


    @RequestMapping("/getArticlesByCreateTime")
    public List<ArticleDetail> getArticlesByCreateTime(){
        return articleService.selectArticlesByCreateTimeWithSummary();
    }

    @RequestMapping("/getArticlesByViewsCount")
    public List<ArticleDetail> selectArticlesByViewsCount(){
        return articleService.selectArticlesByViewsWithSummary();
    }

    @RequestMapping("/selectArticleByArticleId")
    public ArticleDetail selectArticleByArticleId(Integer articleId){
        return articleService.selectArticleByArticleId(Long.valueOf(articleId));
    }

    @RequestMapping("/getArticleCount")
    public Integer getArticleCount(){
        return articleService.selectArticleCount();
    }

    @RequestMapping("/insertArticle")
    public boolean insertArticle(Article article, HttpServletRequest request){
        Collections.list(request.getHeaderNames()).forEach(headerName -> {
            System.out.println(headerName + "=" + request.getHeader(headerName));
        });
        String token = request.getHeader("user_token_key");
        Integer userId = JwtUtils.getUserInfoID(token);
        Article article1 = new Article();
        article1.setUserId(Long.valueOf(userId));
        article1.setTitle(article.getTitle());
        article1.setContent(article.getContent());
        article1.setTopicId(article.getTopicId());
        //返回的是文章id
        Integer result = articleService.insertArticle(article1);
        if(result>0){
            //插入关系
            ArticleTopic articleTopic = new ArticleTopic();
            articleTopic.setArticleId(Long.valueOf(result));
            articleTopic.setTopicId(article.getTopicId());

            articleTopicService.insertArticleTopic(articleTopic);
            return true;
        }else {
            return false;
        }

    }
}
